//引入用户数据库模块
const UserModel_DB = require("../models/UserModel_DB")
//引入保存日志父类
//const ParentController = require("./ParentController")
//引入发送前端工具
const Response = require("../utils/ResponseEntity")
//引入加密
const { getMD5 } = require("../utils/crypto")
//引入身份凭证插件
const jwt = require("jsonwebtoken")
//引入文件上传工具
const { moveFiles, deleteFiles } = require("../utils/handleFile")
//。。。
//这个类提供行为，专门处理user这个对象业务
//。。。
//Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoieGlhb2ZlaSIsImlhdCI6MTY3MTQxNzkxNCwiZXhwIjoxNjcxNzc3OTE0fQ.Qdo-6-3TJFyHLdw4uKEpIKHNli1n9atV3YRnzJWTKP8
class UserController {
    //查询所有用户
    async findAll(req, res, next) {
        try {
            const data = await UserModel_DB.find()
            if (data.length) res.send(Response.success({ msg: "查询成功", data: data }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(ResponseEntity.error({ msg: "服务器错误" }))
        }
    }

    //登录
    async login(req, res, next) {
        try {
            let { name, password } = req.body
            if (name, password) {
                //密码加密
                password = getMD5(password, name)
                //查询数据库是否有该用户
                const data = await UserModel_DB.find({ name, password })
                console.log(data);
                if (data.length) {
                    //生成身份凭证
                    //第一个参数生成保存用户自己信息
                    //第二个参数screct密钥
                    //设置过期时间，单位s秒
                    const token = jwt.sign({ name }, "zheshimiyao", { expiresIn: 60 * 6000 })
                    //token凭证发给后端
                    res.send(Response.success({ msg: "登录成功", data: "Bearer " + token }))
                } else res.send(Response.error({ msg: "登陆失败" }))
            } else res.send(Response.error({ msg: "数据为空" }))
        } catch (error) {
            console.log(error);
            res.send(ResponseEntity.error({ msg: "服务器错误" }))
        }
    }

    //注册
    register = async (req, res, next) => {
        try {
            let { name, password } = req.body
            if (name && password) {
                //查询用户名是否存在
                const result = await UserModel_DB.find({ name })
                if (result.length) res.send(Response.error({ msg: "用户名已存在" }))
                else {
                    //密码加密
                    password = getMD5(password, name)
                    //在数据库添加用户信息（返回对象）
                    const boo = await UserModel_DB.create({
                        name,
                        password,
                        phone: "13333333333",
                        gender: "男",
                        avatar: ""
                    })
                    if (boo._id) res.send(Response.success({ msg: "注册成功", data: boo }))
                    else res.send(ResponseEntity.error({ msg: "注册失败" }))
                }
            } else res.send(ResponseEntity.error({ msg: "注册失败" }))
        } catch (error) {
            console.log(error);
            res.send(ResponseEntity.error({ msg: "服务器错误" }))
        }
    }

    //修改密码
    updatePwd = async (req, res, next) => {
        try {
            //接收旧密码，新密码
            let { oldPwd, newPwd } = req.body
            const token = req.get("Authorization")
            const { name } = jwt.verify(token.split(" ")[1], "zheshimiyao")
            if (oldPwd, newPwd, name) {
                //找到该用户
                const data = await UserModel_DB.findOne({ name })
                //旧密码加密
                oldPwd = getMD5(oldPwd, name)
                //新密码加密
                newPwd = getMD5(newPwd, name)
                if (oldPwd == data.password) {
                    //修改密码
                    await UserModel_DB.updateOne(
                        { name: name },
                        { password: newPwd }
                    )
                    res.send(Response.success({ msg: "修改成功" }))
                } else res.send(Response.error({ msg: "旧密码有误" }))
            } else res.send(Response.error({ msg: "输入不能为空" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //得到用户信息
    async getUserInfo(req, res, next) {
        try {
            const token = req.get("Authorization")
            const { name } = jwt.verify(token.split(" ")[1], "zheshimiyao")
            const data = await UserModel_DB.findOne({ name })
            if (data._id) res.send(Response.success({ msg: "查询成功", data  }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(ResponseEntity.error({ msg: "服务器出错！！" }))
        }
    }

    //修改用户信息
    async updateUserInfo(req, res, next) {
        try {
            //接收学生id ，姓名 ，性别
            const { studentId, name, gender } = req.body
            console.log(studentId, name, gender);
            if (name) {
                await UserModel_DB.updateOne(
                    { _id: studentId },
                    { name: name }
                )
            }
            if (gender) {
                await UserModel_DB.updateOne(
                    { _id: studentId },
                    { gender: gender }
                )
            }
            const data = await UserModel_DB.findOne({ _id: studentId })
            console.log("data" + data);
            res.send(Response.success({ msg: "修改成功", data }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //修改头像
    async updateUserIcon(req, res) {
        try {
            //学生id
            const { id, avatar } = req.body
            const data = await UserModel_DB.updateOne({ _id: id }, { avatar })
            moveFiles({
                fromPath: "./public/temp",
                toPath: "./public/images",
                filename: avatar
            })
            deleteFiles("./public/temp")
            res.send(Response.success({ msg: "修改成功" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器报错" }))
        }
    }
}

const user = new UserController()
module.exports = user